<template>
  <div id="map"></div>
</template>

<script>
// import * as LiBaiLife from './text100.js';
import mapboxgl from "mapbox-gl";
import store from "../../store/index.js";
import http from "@/utils/request.js";
import * as turf from '@turf/turf';
import * as d3 from "d3";

mapboxgl.accessToken = "pk.eyJ1Ijoid3p5YW5ndXN0IiwiYSI6ImNscDl3a3JjMDAxeDMycXA5eXhoYnp5MW0ifQ.pPP33ps1FwkT96cZT_NDNQ";

export default {
  name: 'MapBoxDemo',
  data() {
    return {
      num: 0,
    }
  },
  methods: {
    // Haversine公式算法: 根据经纬度计算距离
    //(lon为经度,lat为纬度)
    Haversine(lon1, lat1, lon2, lat2) {
      Number.prototype.deg2rad = function (deg) {
        return deg * (Math.PI / 180);
      };
      var dLat = (0).deg2rad(lat2 - lat1);
      var dLon = (0).deg2rad(lon2 - lon1);
      var a =
        Math.sin(dLat / 2) * Math.sin(dLat / 2) +
        Math.cos((0).deg2rad(lat1)) *
        Math.cos((0).deg2rad(lat2)) *
        Math.sin(dLon / 2) *
        Math.sin(dLon / 2);
      var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
      return c * 6378;
    },
  },
  mounted() {
    // LiBaiLife.text100()
    var city = {
      雁门关: {
        number: 0,
        lat: [11,22],
        pos: 0
      },
    };
    var markers = [];
    //在这里读取本地JSON文件
    var mainCity;
    var Chronology;
    var data3;
    http.get('/user/map').then(res => {
      mainCity = res.data.mainCity;
      Chronology = res.data.Chronology
      data3 = res.data.data3
    })
    const map = new mapboxgl.Map({
      container: "map",
      // 从地图盒的核心样式中进行选择，或使用地图盒工作室制作自己的样式
      style: "mapbox://styles/wzyangust/clpcmno2c00ae01p99jd8910q",
      pitch: 20, // 设置倾斜程度
      center: [103.8, 30.4],
      zoom: 7,
    });



    map.loadImage("picture/figureImage/李白.png", (error, image) => {
      if (error) throw error;
      if (!map.hasImage("locusImage")) {
        map.addImage("locusImage", image);
      }
    });
    map.on('styleimagemissing', async (e) => {
      let el = new Image(100, 100);
      el.className = 'marker';
      el.src = await "picture/figureImage/李白.png";
      map.addImage(e.id, el);
    });



    map.on("load", async () => {
      // 向地图添加缩放和旋转控件, 默认为右上角
      map.addControl(new mapboxgl.NavigationControl());
      // 向地图添加比例尺, 默认左下角
      map.addControl(new mapboxgl.ScaleControl({ maxWidth: 75, unit: "metric" }));
      // 向地图添加全屏按钮,默认右上角
      map.addControl(new mapboxgl.FullscreenControl());

      // 定义源数据
      let point = {
        type: "FeatureCollection",
        features: [
          {
            type: "Feature",
            properties: {
              bearing: 0,
              name: "",
            },
            geometry: {
              type: "Point",
              coordinates: [104.732, 31.774],
            },
          },
        ],
      };
      let data = {
        type: "FeatureCollection",
        features: [
          {
            type: "Feature",
            geometry: {
              type: "LineString",
              coordinates: [[104.732, 31.774]],
            },
          },
        ],
      };
      // 处理数据
      // 处理显示的城市
      for (let key in mainCity) {
        for (let i in mainCity[key]) {
          city[mainCity[key][i]] = {
            number: 0,
            lat: [11,22],
            pos: 0
          }
          // city[mainCity[key][i]][number] = 0;
        }
      }
      // 添加点位
      var startTime = store.state.timeline;

      var startI = 0,
        currentI = 0;
      var startJ = 0;
      for (let i = 0; i < data3.length; i++) {
        if (data3[i][2] == startTime) {
          startI = currentI;
          startJ = i;
          startTime = 123;
        }
        if (i == 0) {
          for (let j = 1; j <= 20; j++) {
            data.features[0].geometry.coordinates.push([
              data3[i][0] + (Math.random() % 0.02) - 0.01,
              data3[i][1] + (Math.random() % 0.02) - 0.01,
            ]);
            currentI++;
          }
        } else {
          let lon1 = data3[i - 1][0];
          let lon2 = data3[i][0] - data3[i - 1][0];
          let lat1 = data3[i - 1][1];
          let lat2 = data3[i][1] - data3[i - 1][1];
          let distance = turf.distance(
            turf.point([data3[i - 1][0], data3[i - 1][1]]),
            turf.point([data3[i][0], data3[i][1]]),
            { units: "kilometers" }
          );
          let n = parseInt(distance / 2.8);
          for (let j = 1; j <= n; j++) {
            if (j == 1) data.features[0].geometry.coordinates.push([lon1, lat1]);
            else
              data.features[0].geometry.coordinates.push([
                lon1 + (Math.random() % 0.02) - 0.01,
                lat1 + (Math.random() % 0.02) - 0.01,
              ]);
            lon1 += lon2 / n;
            lat1 += lat2 / n;
            currentI++;
          }
        }
      }
      // 初始点
      let i = startI,
        j = startJ;
      if (startI != 0) i--;
      if (startJ != 0) j--;
      store.state.currentProgress = i;
      // 设置视口
      const coordinates = data.features[0].geometry.coordinates;
      data.features[0].geometry.coordinates = [coordinates[i]];
      point.features[0].geometry.coordinates = coordinates[i];

      if (i < coordinates.length && i > 25) {
        for (let j = 1; j < i; j++) {
          let dist = turf.distance(
            turf.point(coordinates[j]),
            turf.point(coordinates[j - 1]),
            { units: "kilometers" }
          );
          store.state.kilometer += Number(
            String(dist).replace(/^(.*\..{2}).*$/, "$1")
          );
          store.state.kilometer = Number(
            String(store.state.kilometer).replace(/^(.*\..{2}).*$/, "$1")
          );
        }
      }

      map.jumpTo({ center: coordinates[i], zoom: 7.2 });
      map.setPitch(20);

      map.addSource("trace", { type: "geojson", data: data });
      map.addSource("point", { type: "geojson", data: point });
      //这里是读取移动线条的属性
      map.addLayer({
        id: "trace",
        type: "line",
        source: "trace",
        paint: {
          // 'line-color': "#737cbd",
          "line-color": "#303030",
          "line-opacity": 0.8,
          "line-width": 8,
        },
      });


      map.addLayer({
        id: "point",
        source: "point",
        type: "symbol",
        layout: {
          // 此图标是地图框街道样式的一部分。
          // 要查看Mapbox样式中可用的所有图像，请在Mapbox Studio中打开该样式，然后单击“图像”选项卡。
          // 要在运行时向样式添加新图像，请参阅 https://docs.mapbox.com/mapbox-gl-js/example/add-image/
          "icon-image": "locusImage",
          "icon-size": 0.2,
          "icon-rotate": ["get", "bearing"],
          "icon-rotation-alignment": "map",
          "icon-allow-overlap": true,
          "icon-ignore-placement": true,
          "text-field": "前往{name}",
          'text-offset': [2, 2],
          // 'text-anchor':'top',
          'text-size': 14
        },
        paint: {
          "text-color": 'rgba(255,0,255,1)'
        }
      });



      store.state.isclose = false;
      store.state.currentRouter = 3;

      // 动画跑图
      const timer = setInterval(() => {
        if (store.state.isclose) {
          for (let k = 0; k < markers.length; k++) {
            markers[k].remove();
          }
          map.removeLayer("point");
          map.removeSource("point");
          map.removeLayer("trace");
          map.removeSource("trace");
          store.state.currentProgress = 0;
          window.clearInterval(timer);
        }
        else if (store.state.currentRouter != 3) {
          store.state.currentProgress = 0;
          window.clearInterval(timer);
        }
        else if (store.state.isPause) {
          if (i < coordinates.length && j < data3.length) {
            data.features[0].geometry.coordinates.push(coordinates[i]);
            map.getSource("trace").setData(data);

            point.features[0].geometry.coordinates = coordinates[i];
            point.features[0].properties.name = data3[j][3];

            map.getSource("point").setData(point);


            // 排除后续插入点(双指针查找算法)
            if (coordinates[i][0] == data3[j][0]) {
              console.log(city)
              console.log(city["雁门关"].number);
              // 诗词提及地点
              if (city[data3[j][3]].number >= 0) {
                let points = coordinates[i]; // 捕获结果坐标
                city[data3[j][3]].lat = points;
                city[data3[j][3]].pos = markers.length;
                point.features[0].properties.name = data3[j][3];

                var colars = Array(10).fill().map((_, index) => index + 1);

                // 定义输入域（数据范围）
                var domain = [0, 10];

                // 定义输出颜色范围
                var colorRange = ['red', 'purple', 'black'];
                var sizeRange = [20, 100]


                // 定义线性颜色比例尺
                var colorScale = d3.scaleLinear()
                  .domain(domain) // 设置输入域
                  .range(colorRange) // 设置输出颜色范围

                var sizeScale = d3.scaleLinear()
                  .domain(domain) // 设置输入域
                  .range(sizeRange); // 设置输出域

                // 使用颜色比例尺将数据映射到颜色值
                var scaledColors = colars.map(function (d) {
                  return colorScale(d);
                });
                var scaledData = colars.map(function (d) {
                  return sizeScale(d);
                });
                let ela = document.createElement('div');
                let elb = document.createElement('div');
                elb.textContent = data3[j][3];
                elb.style.color = '#0000ff';
                elb.style.fontSize = '16px';
                elb.style.fontFamily = '楷体';
                elb.style.fontWeight = '900';
                ela.style.background = scaledColors[city[data3[j][3]].number];
                ela.style.height = scaledData[city[data3[j][3]].number] + "px";
                ela.style.width = scaledData[city[data3[j][3]].number] + "px";
                ela.style.borderRadius = '1000px';
                if (j != data3.length - 1 &&city[data3[j][3]].number == 0) {
                  markers.push(
                    new mapboxgl.Marker(ela)
                      .setLngLat(points)
                      .addTo(map)
                  );
                  markers.push(
                    new mapboxgl.Marker(elb)
                      .setLngLat(points)
                      .setOffset([-25, 25])
                      .addTo(map)
                  );
                }
                else if(j != data3.length - 1 &&city[data3[j][3]].number > 0) {
                  markers[city[data3[j][3]].pos].remove()
                  markers[city[data3[j][3]].pos+1].remove()
                  markers.splice(city[data3[j][3]].pos,2)
                  markers.push(
                    new mapboxgl.Marker(ela)
                      .setLngLat(points)
                      .addTo(map)
                  );
                  markers.push(
                    new mapboxgl.Marker(elb)
                      .setLngLat(points)
                      .setOffset([-25, 25])
                      .addTo(map)
                  );
                }
                console.log(city[data3[j][3]].number);
                city[data3[j][3]].number += 1;
                console.log(city[data3[j][3]].number);
                console.log(markers, markers.length)
                // if(markers.length >= 14) {
                //   markers[0].remove();
                //   markers[1].remove();
                //   markers.shift();
                //   markers.shift();
                // }
              }
              // for (let k = 0; k < markers.length; k++) {
              //   if (this.Haversine(markers[k].getLngLat().lng, markers[k].getLngLat().lat, coordinates[i][0], coordinates[i][1]) > 200) {
              //     markers[k].remove();
              //   }
                
              // }
              j++;
              store.state.time = data3[j][2];
              store.state.year = Chronology[store.state.time].time;
              store.state.things = Chronology[store.state.time].events;
            }
            map.panTo(coordinates[i]);
            i++;
            store.state.currentProgress++;
            // 实时更新里程数
            if (i < coordinates.length && i > 25) {
              let dist = turf.distance(
                turf.point(coordinates[i]),
                turf.point(coordinates[i - 1]),
                { units: "kilometers" }
              );
              store.state.kilometer += Number(
                String(dist).replace(/^(.*\..{2}).*$/, "$1")
              );
              store.state.kilometer = Number(
                String(store.state.kilometer).replace(/^(.*\..{2}).*$/, "$1")
              );
            }
          } else {
            for (let k = 1; k < markers.length; k++) {
              markers[k].remove();
            }
            map.removeLayer("point");
            map.removeSource("point");
            window.clearInterval(timer);
          }
        }
        else {
          map.removeLayer("point");
          map.addLayer({
            id: "point",
            source: "point",
            type: "symbol",
            layout: {
              // 此图标是地图框街道样式的一部分。
              // 要查看Mapbox样式中可用的所有图像，请在Mapbox Studio中打开该样式，然后单击“图像”选项卡。
              // 要在运行时向样式添加新图像，请参阅 https://docs.mapbox.com/mapbox-gl-js/example/add-image/
              "icon-image": "locusImage",
              "icon-size": 0.2,
              "icon-rotate": ["get", "bearing"],
              "icon-rotation-alignment": "map",
              "icon-allow-overlap": true,
              "icon-ignore-placement": true,
              "text-field": "前往{name}",
              'text-offset': [2, 2],
              'text-size': 14
            },
            paint: {
              "text-color": 'rgba(255,0,0,1)'
            }
          });
        }
      }, 40);
    });
  }
}
</script>

<style scoped></style>
